<template>
  <div class="article-list-page">
    <!-- 搜索栏 -->
    <div class="search-section">
      <div class="search-bar">
        <input
          v-model="searchParams.title"
          type="text"
          placeholder="请搜索文章标题..."
          class="search-input"
        />
        <n-button type="primary" @click="handleSearch" class="search-btn"> 搜索 </n-button>
      </div>
    </div>

    <!-- 筛选条件区域 -->
    <div class="filter-section">
      <div class="filter-header" @click="toggleFilters">
        <h3>筛选条件</h3>
        <span class="toggle-icon" :class="{ expanded: filtersExpanded }">▼</span>
      </div>

      <div class="filter-content" :class="{ expanded: filtersExpanded }">
        <!-- 文章分类 -->
        <div class="filter-group">
          <label class="filter-label">文章分类</label>
          <div class="filter-options">
            <button
              v-for="category in categoryOptions"
              :key="category.value"
              @click="selectFilter('category', category.value)"
              :class="['filter-option', { active: searchParams.category === category.value }]"
            >
              {{ category.label }}
            </button>
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="filter-actions">
          <button @click="clearFilters" class="clear-btn">清除筛选</button>
        </div>
      </div>
    </div>

    <!-- 排序和结果统计 -->
    <div class="results-header">
      <div class="results-info">
        <span>共找到 {{ pages }} 篇文章</span>
      </div>
    </div>

    <div v-if="loading" class="loading">
      <div class="spinner"></div>
      <p>正在加载文章数据...</p>
    </div>
    <div v-else-if="dataList.length === 0" class="empty-state">
      <div class="empty-icon">📄</div>
      <h2 class="empty-title">暂无文章</h2>
      <p class="empty-desc">该分类无任何文章</p>
    </div>

    <!-- 文章列表 -->
    <div class="article-list">
      <div
        v-for="article in dataList"
        :key="article.id"
        class="article-card"
        @click="viewArticle(article.id)"
      >
        <div class="article-image-container">
          <n-image
            v-if="article.coverUrl"
            :src="article.coverUrl"
            class="article-image"
            :img-props="{ style: { width: '100%', height: '100%', objectFit: 'cover' } }"
          />
          <div v-else class="no-image">
            {{ article.title }}
          </div>
          <div class="article-badge" v-if="article.isHot">🔥 热门</div>
          <div class="article-category">{{ article.categoryName }}</div>
        </div>
        <div class="article-content">
          <h3 class="article-title">{{ article.title }}</h3>
          <p class="article-description">{{ article.description || '无描述' }}</p>
          <div class="article-meta">
            <div class="article-stats">
              <span class="views">👁️ {{ article.viewCount || 0 }} 次阅读</span>
              <span class="date">📅 {{ article.publishDate || '未知日期' }}</span>
              <span class="author" v-if="article.author">✍️ {{ article.author }}</span>
            </div>
          </div>
          <div class="article-footer">
            <div class="article-tags">
              <span v-for="tag in article.tags" :key="tag" class="article-tag">
                {{ tag }}
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="flex justify-center margin-top-20">
      <n-pagination
        v-model:page="pageNum"
        :page-count="pages"
        size="large"
        :on-update:page="pageUpdate"
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { ref, onMounted } from 'vue';
  import { useRouter } from 'vue-router';

  const router = useRouter();

  const filtersExpanded = ref(false);
  const searchParams = ref({
    title: '',
    category: '',
  });

  // 文章分类选项
  const categoryOptions = ref([
    { label: '机器学习', value: 'machine_learning' },
    { label: '深度学习', value: 'deep_learning' },
    { label: '自然语言处理', value: 'nlp' },
    { label: '计算机视觉', value: 'computer_vision' },
    { label: 'AI应用', value: 'ai_application' },
    { label: 'AI工具', value: 'ai_tools' },
    { label: '行业动态', value: 'industry_news' },
  ]);

  // 文章类型定义
  interface Article {
    id: number;
    title: string;
    description: string;
    coverUrl: string;
    category: string;
    categoryName: string;
    viewCount: number;
    publishDate: string;
    author: string;
    tags: string[];
    isHot: boolean;
  }

  // 生成假数据
  function generateMockArticles(): Article[] {
    const categories = [
      { name: '机器学习', value: 'machine_learning' },
      { name: '深度学习', value: 'deep_learning' },
      { name: '自然语言处理', value: 'nlp' },
      { name: '计算机视觉', value: 'computer_vision' },
      { name: 'AI应用', value: 'ai_application' },
      { name: 'AI工具', value: 'ai_tools' },
      { name: '行业动态', value: 'industry_news' },
    ];

    const titles = [
      'ChatGPT 4.0 全面解析：从原理到应用',
      'Transformer 架构深度剖析',
      '大语言模型训练实战指南',
      'AI 绘画工具 Midjourney 使用教程',
      '机器学习算法优化技巧',
      '深度学习在图像识别中的应用',
      '自然语言处理最新进展',
      'AI 辅助编程工具推荐',
      '计算机视觉技术前沿',
      'AI 在医疗领域的应用案例',
      '强化学习实战项目',
      '神经网络架构搜索',
      'AI 模型部署最佳实践',
      '数据科学工作流程优化',
      'AI 伦理与安全探讨',
    ];

    const descriptions = [
      '深入探讨 ChatGPT 4.0 的技术原理、应用场景和未来发展趋势，帮助读者全面了解这一革命性 AI 技术。',
      '详细解析 Transformer 架构的设计思想、核心组件和实现细节，适合有一定基础的开发者学习。',
      '从零开始构建大语言模型训练流程，包括数据准备、模型设计、训练优化等关键环节。',
      '手把手教你使用 Midjourney 创作高质量 AI 艺术作品，包含实用技巧和案例分享。',
      '分享机器学习算法优化的实战经验，涵盖特征工程、超参数调优、模型融合等核心内容。',
      '探索深度学习在图像识别领域的最新应用，包括目标检测、图像分割等前沿技术。',
      '介绍自然语言处理领域的最新研究成果和技术突破，展望未来发展方向。',
      '推荐几款优秀的 AI 辅助编程工具，提升开发效率和代码质量。',
      '了解计算机视觉技术的最新进展，包括 3D 视觉、视频理解等前沿方向。',
      '通过真实案例了解 AI 在医疗诊断、药物研发等领域的应用价值和挑战。',
      '通过实际项目学习强化学习的核心概念和应用方法，掌握实战技能。',
      '探索神经网络架构搜索技术，了解如何自动设计最优网络结构。',
      '分享 AI 模型在生产环境中的部署经验，包括性能优化、监控维护等。',
      '优化数据科学工作流程，提高数据处理和分析的效率。',
      '探讨 AI 技术发展中的伦理问题和安全挑战，思考负责任的 AI 发展路径。',
    ];

    const authors = ['张教授', '李博士', '王研究员', '刘工程师', '陈专家', '赵学者'];
    const tags = [
      ['AI', '机器学习'],
      ['深度学习', '神经网络'],
      ['NLP', '大语言模型'],
      ['AI工具', '实用教程'],
      ['算法', '优化'],
      ['计算机视觉', '图像处理'],
      ['自然语言处理', '文本分析'],
      ['开发工具', '效率提升'],
      ['前沿技术', '研究进展'],
      ['行业应用', '案例分享'],
      ['强化学习', '实战项目'],
      ['模型设计', '架构优化'],
      ['工程实践', '部署运维'],
      ['数据科学', '工作流程'],
      ['AI伦理', '安全'],
    ];

    const articles: Article[] = [];
    for (let i = 0; i < 50; i++) {
      const category = categories[i % categories.length];
      const titleIndex = i % titles.length;
      articles.push({
        id: i + 1,
        title:
          titles[titleIndex] +
          (i >= titles.length ? ` (${Math.floor(i / titles.length) + 1})` : ''),
        description: descriptions[titleIndex],
        coverUrl: `https://picsum.photos/400/250?random=${i}`,
        category: category.value,
        categoryName: category.name,
        viewCount: Math.floor(Math.random() * 10000) + 100,
        publishDate: new Date(
          Date.now() - Math.random() * 365 * 24 * 60 * 60 * 1000
        ).toLocaleDateString('zh-CN'),
        author: authors[Math.floor(Math.random() * authors.length)],
        tags: tags[titleIndex],
        isHot: Math.random() > 0.7,
      });
    }
    return articles;
  }

  const allArticles = ref<Article[]>(generateMockArticles());

  function toggleFilters() {
    filtersExpanded.value = !filtersExpanded.value;
  }

  function selectFilter(type: any, value: any) {
    if (searchParams.value[type] === value) {
      searchParams.value[type] = '';
    } else {
      searchParams.value[type] = value;
    }

    handleSearch();
  }

  function clearFilters() {
    searchParams.value = {
      title: '',
      category: '',
    };
    handleSearch();
  }

  function viewArticle(articleId: any) {
    // 跳转到文章详情页
    router.push({
      name: 'official_detail',
      query: {
        id: articleId,
      },
    });
  }

  // 分页参数
  const pageNum = ref(1);
  const pageSize = 10;
  const loading = ref(false);
  const isLastPage = ref(false);
  const pages = ref(0);
  const dataList = ref<any[]>([]);

  function handleSearch() {
    resetPage();
    loadData();
  }

  function loadData() {
    if (loading.value) return;

    loading.value = true;
    try {
      // 模拟 API 延迟
      setTimeout(() => {
        let filteredArticles: Article[] = [...allArticles.value];

        // 按标题搜索
        if (searchParams.value.title) {
          filteredArticles = filteredArticles.filter((article) =>
            article.title.toLowerCase().includes(searchParams.value.title.toLowerCase())
          );
        }

        // 按分类筛选
        if (searchParams.value.category) {
          filteredArticles = filteredArticles.filter(
            (article) => article.category === searchParams.value.category
          );
        }

        // 计算总页数
        const total = filteredArticles.length;
        pages.value = Math.ceil(total / pageSize);

        // 分页
        const start = (pageNum.value - 1) * pageSize;
        const end = start + pageSize;
        dataList.value = filteredArticles.slice(start, end);

        if (dataList.value.length < pageSize) {
          isLastPage.value = true;
        } else {
          isLastPage.value = false;
        }

        loading.value = false;
      }, 300); // 模拟网络延迟
    } catch (error) {
      console.error('error:', error);
      loading.value = false;
    }
  }

  function resetPage() {
    pageNum.value = 1;
    isLastPage.value = false;
    dataList.value = [];
  }

  function pageUpdate(num: any) {
    pageNum.value = num;
    loadData();
  }

  onMounted(() => {
    loadData();
  });
</script>

<style scoped>
  .article-list-page {
    max-width: 1500px;
    margin: 0 auto;
    padding: 20px;
  }

  /* 搜索栏 */
  .search-section {
    margin-bottom: 30px;
  }

  .search-bar {
    display: flex;
    align-items: center;
    gap: 10px;
    max-width: 600px;
    margin: 0 auto;
  }

  .search-input {
    flex: 1;
    height: 45px;
    padding: 0 10px;
    border: 2px solid #e2e8f0;
    border-radius: 8px;
    font-size: 16px;
    transition: border-color 0.3s;
  }

  .search-input:focus {
    outline: none;
    border-color: #d174df;
    box-shadow: 0 0 0 4px rgba(209, 116, 223, 0.1);
    background: white;
  }

  .search-input:placeholder {
    color: #9ca3af;
  }

  .search-btn {
    height: 40px;
  }

  /* 筛选区域 */
  .filter-section {
    background: white;
    border: 1px solid #e2e8f0;
    border-radius: 8px;
    margin-bottom: 30px;
    overflow: hidden;
  }

  .filter-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 20px;
    background: #f7fafc;
    cursor: pointer;
    transition: background-color 0.3s;
  }

  .filter-header:hover {
    background: #edf2f7;
  }

  .filter-header h3 {
    margin: 0;
    font-size: 1rem;
    color: #2d3748;
  }

  .toggle-icon {
    font-size: 12px;
    color: #718096;
    transition: transform 0.3s;
  }

  .toggle-icon.expanded {
    transform: rotate(180deg);
  }

  .filter-content {
    max-height: 0;
    overflow: hidden;
    transition: max-height 0.3s ease-out;
    display: none;
  }

  .filter-content.expanded {
    max-height: 1000px;
    display: block;
    padding: 20px;
  }

  .filter-group {
    display: flex;
    align-items: flex-start;
    margin-bottom: 20px;
    gap: 20px;
  }

  .filter-label {
    min-width: 100px;
    font-weight: 600;
    color: #2d3748;
    padding-top: 8px;
  }

  .filter-options {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    flex: 1;
  }

  .filter-option {
    padding: 8px 16px;
    border: 1px solid #e2e8f0;
    border-radius: 20px;
    background: white;
    color: #4a5568;
    cursor: pointer;
    transition: all 0.3s;
    font-size: 14px;
  }

  .filter-option:hover {
    border-color: #3182ce;
    color: #3182ce;
  }

  .filter-option.active {
    background: #3182ce;
    color: white;
    border-color: #3182ce;
  }

  .filter-actions {
    display: flex;
    gap: 10px;
    justify-content: flex-end;
    margin-top: 20px;
    padding-top: 20px;
    border-top: 1px solid #e2e8f0;
  }

  .clear-btn {
    padding: 10px 20px;
    border: none;
    border-radius: 6px;
    cursor: pointer;
    font-size: 14px;
    transition: background-color 0.3s;
    background: #f7fafc;
    color: #4a5568;
    border: 1px solid #e2e8f0;
  }

  .clear-btn:hover {
    background: #edf2f7;
  }

  /* 结果统计 */
  .results-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 15px 0;
    border-bottom: 1px solid #e2e8f0;
  }

  .results-info {
    color: #4a5568;
    font-size: 14px;
  }

  /* 文章列表 */
  .article-list {
    display: flex;
    flex-direction: column;
    gap: 20px;
  }

  .article-card {
    display: flex;
    background: white;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    transition: all 0.3s;
    cursor: pointer;
    gap: 20px;
  }

  .article-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
  }

  .article-image-container {
    position: relative;
    width: 300px;
    min-width: 300px;
    height: 200px;
    overflow: hidden;
    flex-shrink: 0;
  }

  .article-image-container .article-image {
    width: 100%;
    height: 100%;
  }

  .no-image {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    font-size: 18px;
    font-weight: 600;
    padding: 20px;
    text-align: center;
  }

  .article-badge {
    position: absolute;
    top: 10px;
    left: 10px;
    background: rgba(255, 69, 0, 0.9);
    color: white;
    padding: 4px 8px;
    border-radius: 12px;
    font-size: 12px;
    font-weight: 600;
    z-index: 1;
  }

  .article-category {
    position: absolute;
    top: 10px;
    right: 10px;
    background: rgba(0, 0, 0, 0.7);
    color: white;
    padding: 4px 8px;
    border-radius: 12px;
    font-size: 12px;
    z-index: 1;
  }

  .article-content {
    flex: 1;
    padding: 20px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
  }

  .article-title {
    font-size: 1.3rem;
    font-weight: 600;
    color: #2d3748;
    margin-bottom: 12px;
    line-height: 1.4;
  }

  .article-description {
    color: #718096;
    font-size: 15px;
    line-height: 1.6;
    margin-bottom: 16px;
    display: -webkit-box;
    -webkit-line-clamp: 3;
    line-clamp: 3;
    -webkit-box-orient: vertical;
    overflow: hidden;
    flex: 1;
  }

  .article-meta {
    margin-bottom: 12px;
  }

  .article-stats {
    display: flex;
    gap: 20px;
    font-size: 13px;
    color: #718096;
    flex-wrap: wrap;
  }

  .article-stats span {
    display: flex;
    align-items: center;
    gap: 4px;
  }

  .article-footer {
    display: flex;
    align-items: center;
    margin-top: auto;
  }

  .article-tags {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
  }

  .article-tag {
    font-size: 12px;
    color: #3182ce;
    background: #ebf8ff;
    padding: 4px 10px;
    border-radius: 12px;
    transition: all 0.3s;
  }

  .article-tag:hover {
    background: #bee3f8;
    color: #2c5282;
  }

  /* 响应式设计 */
  @media (max-width: 768px) {
    .article-card {
      flex-direction: column;
    }

    .article-image-container {
      width: 100%;
      height: 200px;
    }

    .filter-group {
      flex-direction: column;
      gap: 10px;
    }

    .filter-label {
      min-width: auto;
    }

    .results-header {
      flex-direction: column;
      gap: 10px;
      align-items: flex-start;
    }
  }

  .loading {
    text-align: center;
    padding: 40px;
    color: #7f8c8d;
  }

  .spinner {
    border: 4px solid rgba(0, 0, 0, 0.1);
    border-left-color: #4cb69b;
    border-radius: 50%;
    width: 40px;
    height: 40px;
    animation: spin 1s linear infinite;
    margin: 50px auto 20px;
  }

  @keyframes spin {
    to {
      transform: rotate(360deg);
    }
  }

  .empty-state {
    text-align: center;
    padding: 60px 20px;
    color: #7f8c8d;
  }

  .empty-icon {
    font-size: 80px;
    color: #ddd;
    margin-bottom: 20px;
  }

  .empty-title {
    font-size: 24px;
    margin-bottom: 15px;
    color: #95a5a6;
  }

  .empty-desc {
    font-size: 16px;
    max-width: 500px;
    margin: 0 auto 30px;
  }
</style>
